<template>
  <div class="goodForm">
    <el-steps :active="setpIndex" simple @click.native="tagtag">
      <el-step title="1.编辑基本信息" icon="none"></el-step>
      <el-step title="2.编辑销售信息" icon="none"></el-step>
      <el-step title="3.编辑商品信息" icon="none"></el-step>
    </el-steps>
    <!--  -->
    <keep-alive>
      <component ref="componentRef" :good-detail="goodDetail" :is="currentStep" :logisticsId="logisticsId"
        @changeLogisticsId="changeLogisticsId"></component>
    </keep-alive>
    <!--  -->
    <div class="next">
      <el-button v-if="prevStep !== ''" @click="handlePrev" type="primary">上一步</el-button>
      <el-button v-if="nextStep !== ''" @click="handleNext" type="primary">下一步</el-button>
      <template v-if="currentStep === 'NewGoodDetailInfo'">
        <el-button @click="putAway" type="primary">上架</el-button>
        <el-button @click="cancelputAway">取消</el-button>
      </template>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref, Prop } from "vue-property-decorator";
import { editGood, updateGood, putWayGood } from "@/api/good/goods";
import NewGoodBaseInfo from "./NewGoodBaseInfo.vue";
import NewGoodSellInfo from "./NewGoodSellInfo.vue";
import NewGoodDetailInfo from "./NewGoodDetailInfo.vue";
import storage from "@/libs/storage";

import { Getter } from "vuex-class";

Component.registerHooks(["beforeRouteLeave"]);
interface StepIndicator {
  /** 上一步 */
  prev: string;
  /** 下一步 */
  next: string;
  /** 当前进度 */
  setpIndex: number;
}

/**
 * 规格列表
 */
interface Norms {
  /** 规格值 */
  specs: string;
  /** 指导价 */
  originalPrice: number;
  /** 实售价 */
  price: number;
  /** 商品库存 */
  stock: string;
  /** 商品限购 */
  perLimit: string;
  /** sku图 */
  pic: string;
  /** 初始销量 */
  sale: string;
  /** 商品重量 */
  weight: string;

  id: string;
  lowStock: string;
  memberPrices: any;
  skuRebates: any;
  productId: string;
  skuCode: string;
}

@Component({
  components: {
    NewGoodBaseInfo,
    NewGoodSellInfo,
    NewGoodDetailInfo,
  },
})
export default class NewGoodForm extends Vue {
  @Getter("global/isMall") isMall;

  @Prop({
    type: String,
    default() {
      return "";
    },
  })
  from: any;

  /** 总数据 */
  allFoorm = {} as any;

  /**
   * 商品添加步骤
   */
  stepIndicator: {
    [key: string]: StepIndicator;
  } = {
    NewGoodBaseInfo: {
      prev: "",
      next: "NewGoodSellInfo",
      setpIndex: 0,
    },
    NewGoodSellInfo: {
      prev: "NewGoodBaseInfo",
      next: "NewGoodDetailInfo",
      setpIndex: 1,
    },
    NewGoodDetailInfo: {
      prev: "NewGoodSellInfo",
      next: "",
      setpIndex: 2,
    },
  };

  /** 当前步骤 */
  currentStep = "NewGoodBaseInfo";

  /** 需要提交的数据 */
  goodFormModel = {
    /** 是否新增区域默认投放  0否 1 是 */
    addLaunchArea: 1,
    /** 商品图片 */
    albumPics: "",
    /** 模板属性列表 */
    attribute: "",
    /** 商品属性模板id */
    attributeId: "",
    /** 团长佣金 */
    commanderCommission: "",
    /** 佣金类型状态 (0–金额，1–比例) */
    commissionType: 0,
    /** 商品详情 */
    // detail: "",
    /** 配送方式 */
    distributionMode: 0,
    /** 商品分销设置 */
    distributionSets: [],
    /** 参与接龙 0–未参加，1–已参加 */
    dominoState: 2,
    /** 运费模板ID */
    freightTemplateId: "",
    /** 商品赠送积分 */
    giftPoint: "0",
    id: null,
    /** 投放小区ID */
    launchArea: "",
    /** 限购类型(默认统一规格，0–统一规格，1–统一限购，2–规格限购) */
    limitType: 0,
    /** 商品名称 */
    name: "",
    /** 卖点描述 */
    saleDescribe: "",
    /** 规格是否展开 */
    // openSpecs: "",
    /** 展示图片 */
    pic: "",
    /** 模板属性列表 */
    productAttributes: [],
    /** 展示分类模板 */
    productShowCategorys: [],
    /** 货号 */
    productSn: "",
    /** 供应商ID */
    providerId: "",
    /** 初始销量 */
    sale: "0",
    /** 销售专区 0商超 1拼团 2秒杀 */
    saleMode: "0",
    /** 销售名称 导入用 */
    saleName: "",
    /** 评分 */
    // score:""
    /** 产品服务 */
    serviceIds: "",
    /** 商品库存 */
    skuStocks: [],
    /** 分拣品类ID */
    sortingCategoryId: "",
    /** 状态(默认上架，0–下架（仓库中），1–上架，2–已售完) */
    status: 1,
    /** 商品重量 */
    unit: "克",
    /** 商品视频 */
    videoUrl: "",
    /** 商品长度 */
    weight: "",
    /**分佣类型 */
    useDistribution:1,
    /**佣金数值 */
    distributionAmount:"",
    // 商品多规格信息
    productSpecs: [],
  };

  /** 商品详情 */
  goodDetail: any = null;

  /** 监听选择的运费模板 */
  logisticsId = "";

  /** 是否需要显示重量 */
  isWeight = false;

  checkFlag = true;

  @Ref()
  readonly componentRef: HTMLFormElement;

  get currentStepIndicator(): StepIndicator {
    return this.stepIndicator[this.currentStep];
  }

  get setpIndex(): number {
    return this.currentStepIndicator.setpIndex;
  }

  get prevStep(): string {
    return this.currentStepIndicator.prev;
  }

  get nextStep(): string {
    return this.currentStepIndicator.next;
  }

  mounted() {
    this.getGoodDetail();
  }

  tagtag() {
    console.log("导航点击");
  }

  changeLogisticsId() {
    this.logisticsId = "";
  }

  /**
   * 上一步
   */
  async handlePrev() {
    this.$nextTick(() => {
      this.$el.scrollTop = 0;
    });
    const res = await this.componentRef.getNewForm();
    Object.assign(this.allFoorm, res);
    const prevStep = this.prevStep;
    if (prevStep !== "") {
      this.currentStep = prevStep;
    }
  }

  /**
   * 下一步
   */
  async handleNext() {
    console.log("this.currentStep",this.currentStep);
    
    this.$nextTick(() => {
      this.$el.scrollTop = 0;
    });
    const nextStep = this.nextStep;
    if (nextStep !== "") {
      await this.getGoodFormModel();
      if (this.checkFlag) {
        this.currentStep = nextStep;
      }
    }
  }

  /**
   * 获取商品详情
   */
  async getGoodDetail() {
    if (this.isMall) {
      this.goodFormModel.distributionMode = 1;
    }
    const goodId = this.$route.query.id || this.$route.params.id;
    if (!goodId) {
      return;
    }
    const { data } = await editGood(goodId);
    this.goodDetail = data;
    this.goodFormModel.id = goodId;
  }

  async getGoodFormModel() {
    try {
      const res = await this.componentRef.getFormModel();
      console.log('res',res)
      Object.assign(this.goodFormModel, res);
      const goodFormModel = this.goodFormModel;
      // && this.currentStep=="NewGoodSellInfo" && this.prevStep=="NewGoodBaseInfo"
      console.log("goodFormModel", goodFormModel);
      if (goodFormModel.productSpecs.length > 0) {
        this.checkSku(goodFormModel.skuStocks);
        if (this.goodDetail && this.goodDetail.id) {
          this.checkSetting();
        }
      }
      if (goodFormModel.productSpecs.length==0){
        this.checkFlag=true
      }
      // else {
      //   this.checkUnifiedSpec(goodFormModel);
      // }
      return;
    } catch (error) {
      this.$message.warning({
        message: error || "请将信息填写完整",
      });
      return Promise.reject(error);
    }
  }

  /**
   * 规格内容的二次验证
   */
  checkSku(skuStock) {
    this.checkFlag = true;
    if (skuStock.length === 0) throw new Error("请添加规格值");
    skuStock.forEach((item) => {
      if (this.prevStep === "NewGoodBaseInfo") {
        // 校验sku输入值合理性
        this.checkInputField(item);

        if (Number(item.price) === 0) {
          this.checkFlag = false;
          throw new Error("实售价不能为0");
        }
      }
      if (String(item.price).split(".")[1]) {
        const length = String(item.price).split(".")[1].length;
        if (length > 2) {
          this.checkFlag = false;
          throw new Error("实售价最多保留两位小数");
        }
      }
      if (!item.pic&&this.currentStep==='NewGoodSellInfo') {
        this.checkFlag = false;
        throw new Error("请上传SKU图片");
      }
    });
    if (this.checkFlag) {
      this.checkStock(skuStock);
    }
  }

  checkStock(skuStock) {
    const regs = /^[0-9]*[1-9][0-9]*$/;
    if (this.currentStep === "NewGoodSellInfo") {
      if (this.goodFormModel.limitType === 1) {
        const isImg = skuStock.some((item) => {
          return item.pic === "" || item.pic === undefined || item.pic === null;
        });
        if (isImg) {
          this.$message.error("请输入规格sku图");
          this.checkFlag = false;
          return;
        }
      }
    }
    if (this.prevStep === "NewGoodBaseInfo") {
      if (this.isWeight) {
        const isWeight = skuStock.some((v) => {
          return Number(v.weight) === 0 || v.weight === "";
        });
        if (isWeight) {
          this.$message.error("请输入规格重量");
          this.checkFlag = false;
          return;
        }
      }
      const skuItem = skuStock.some(
        (item) => item.stock === "0" || !regs.test(item.stock),
      );
      if (skuItem) {
        this.$message.error("请输入大于0库存");
        this.checkFlag = false;
        return;
      }
      skuStock.forEach((item) => {
        if (item.stock === "0") {
          this.$message.error("请输入大于0库存");
          this.checkFlag = false;
          return;
        }
        if (!regs.test(item.stock)) {
          this.$message.error("请输入大于0库存");
          this.checkFlag = false;
          return;
        }
      });
    }
  }

  // 校验无规格
  checkUnifiedSpec(goodFormModel) {
    if (this.prevStep === "NewGoodBaseInfo") {
      if (
        !this.checkFieldReg(goodFormModel.price) &&
        goodFormModel.stock !== 0
      ) {
        throw new Error("请输入正确的实售价");
      }
      if (
        !this.checkFieldReg(goodFormModel.price) &&
        goodFormModel.stock !== 0
      ) {
        throw new Error("请输入正确的库存");
      }
    }
  }

  /**
   * 编辑时实售价需大于会员价与返利价格
   */
  checkSetting() {
    if (this.currentStep === "NewGoodSellInfo") {
      const skuList = this.goodFormModel.skuStocks;
      skuList.forEach((skuItem) => {
        if (skuItem.memberType && skuItem.memberType === 1) {
          const vipList = skuItem.memberPrices.map((item) => item.memberPrice);
          const maxPrice = Math.max(...vipList);
          if (Number(skuItem.price) < maxPrice) {
            this.$confirm("您已设置会员价,实售价不得低于最低档会员价", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            });
            this.checkFlag = false;
            return;
          }
        }

        if (skuItem.rebateType && skuItem.rebateType === 1) {
          const rebList = skuItem.skuRebates.map((item) => item.rebatePrice);
          const maxPrice = Math.max(...rebList);
          if (Number(skuItem.price) < maxPrice) {
            this.$confirm("您已设置返利,返利价格不能高于实售价", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            });
            this.checkFlag = false;
          }
        }
      });
    }
  }
  // 校验输入
  checkInputField(skuStockItem) {
    if (
      !this.checkFieldReg(skuStockItem.originalPrice) &&
      skuStockItem.originalPrice !== 0
    ) {
      throw new Error("请输入正确的指导价");
    }
    if (!this.checkFieldReg(skuStockItem.price) && skuStockItem.price !== 0) {
      throw new Error("请输入正确的实售价");
    }
    if (!this.checkFieldReg(skuStockItem.stock) && skuStockItem.stock !== 0) {
      throw new Error("请输入正确的库存");
    }
    if (
      !this.checkFieldReg(skuStockItem.perLimit) &&
      skuStockItem.perLimit !== 0
    ) {
      throw new Error("请输入正确的限购数量");
    }
    if (!this.checkFieldReg(skuStockItem.weight) && skuStockItem.weight !== 0) {
      throw new Error("请输入正确的重量");
    }
  }
  // 校验输入值是否超过两位小数
  // 检验输入值规格
  checkFieldReg(value) {
    let flag = true;
    const priceReg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
    if (!value) {
      flag = false;
    }
    if (!priceReg.test(value)) {
      flag = false;
    }
    return flag;
  }

  /**
   * 上架
   */
  async putAway() {
    this.$parent.$parent.$parent.$parent.saveFlag = true;
    await this.getGoodFormModel();
    storage.delete("formModel");
    const goodFormModel = this.goodFormModel as any;
    goodFormModel.status = 1;
    goodFormModel.place = 0;
    // if (this.from === "csv") {
    // goodFormModel.saleMode =
    //   goodFormModel.saleName === "商超专区" ? "0" : "1";
    // }
    const hasSome = goodFormModel.skuStocks.some((cItem) => {
      return cItem.memberType === 3;
    });
    if (hasSome) {
      goodFormModel.skuStocks.map((sItem) => {
        return (sItem.memberType = 3);
      });
    }
    const saleMode = this.$parent.$parent.$parent.$parent.saleMode;
    try{
      const res = goodFormModel.id
        ? await updateGood(goodFormModel)
        : await putWayGood(goodFormModel);

      if (res.code === 200) {
        this.$message.success(`${goodFormModel.id ? "编辑成功" : "上架成功"}`);
      // this.$router.push({
      //   name:
      //     this.from === "csv"
      //       ? "csvList"
      //       : Number(goodFormModel.saleMode) === 0
      //         ? "Goods"
      //         : "GroupGoods",
      // });
        this.$router.push({
          name: this.from === "csv" ? "csvList" : "Goods",
          params: { saleMode: this.from === "csv" ? "" : saleMode },
        });
      }
    }
    catch(err){
        this.$message.error(err);
    }
  }

  /**
   * 取消上架
   */
  cancelputAway() {
    this.$router.push({ name: "Goods" });
  }
}
</script>

<style lang="scss">
@import "@/assets/styles/goods/index.scss";
.goodForm {
  // height: 740px;
  overflow: auto;
  .topTag {
    display: flex;
    height: 40px;
    border-bottom: 1px solid #eee;
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 40px;
    li {
      padding-left: 20px;
      height: 38px;
      display: flex;
      align-items: center;
      margin-right: 30px;
      cursor: pointer;
      span {
        line-height: 38px;
        display: block;
        padding: 0 20px;
      }
      &.topTag--active span {
        border-bottom: #2d8cf0 2px solid;
        color: #2d8cf0;
      }
    }
  }

  .pageRoll {
    // overflow: auto;
    // overflow-x: hidden;
    // height: 800px;
    padding-bottom: 80px;
  }

  .pageRoll::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
  }

  .navLine {
    margin-top: 25px;
    margin-bottom: 25px;
    height: 40px;
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    padding-left: 15px;
    font-weight: bold;
  }

  .spec {
    margin-left: 40px;
    &__left {
      margin-left: 8px;
    }
  }

  .specitem {
    margin-left: 124px;
    margin-top: 10px;
    &__inp {
      display: flex;
      align-items: flex-end;
      margin-top: 10px;
      &--inside {
        width: 50px;
        margin: 0px 10px;
      }
    }
  }

  .dialogTitle {
    display: flex;
    justify-content: center;
    font-weight: bold;
    font-size: 16px;
  }

  .dialog__line {
    display: flex;
    padding-left: 20px;
    padding-top: 10px;
    justify-content: flex-start;
    align-items: flex-start;
    &__fir {
      width: 100%;
      text-align: right;
      display: flex;
      align-items: center;
    }
    &__sec {
      width: 100%;
      display: flex;
      margin-top: 10px;
      &--head {
        padding: 10px;
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        background-color: #f6f6f6;
      }
      &--body {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #999;
        padding: 10px;
      }
    }
  }

  .add--text {
    line-height: 30px;
    cursor: pointer;
    color: #2d8cf0;
    margin-left: 90px;
    margin-top: 10px;
  }

  .pick--dia {
    display: flex;
    justify-content: space-between;
    padding: 10px 30px;
    background-color: #e9f3fb;
  }

  .pick--input {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 30px;
  }

  .valueName {
    margin-top: 10px;
    width: 620px;
    padding: 20px 20px;
    border: 1px solid #d7d7d7;
    &__noList {
      display: flex;
      justify-content: center;
      color: #d7d7d7;
      font-size: 15px;
      margin-left: 20px;
      margin-top: 20px;
    }
    &__List {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      div {
        color: red;
        cursor: pointer;
      }
    }
  }

  .product {
    margin-top: 10px;
  }

  .productVideo__uploader {
    display: flex;
    align-items: flex-end;
  }

  .productImg__uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .productImg__uploader:hover {
    border-color: #409eff;
  }

  .product__productImg {
    width: 100px;
    height: 100px;
    display: inline-block;
  }

  .product__productVideo {
    width: 250px;
    height: 120px;
    display: inline-block;
  }

  .product__productVideo--uploader--icon {
    font-size: 28px;
    color: #8c939d;
    width: 250px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .product__productImg--uploader--icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 80px;
    text-align: center;
  }

  .product__productImg--uploader--add {
    position: absolute;
    top: 55px;
    left: 20px;
    color: #7f7f7f;
  }

  .productImg-uploader-clear {
    position: absolute;
    right: -0.375rem;
    top: -0.375rem;
    font-size: 20px;
    cursor: pointer;
  }

  .productImg-text {
    position: absolute;
    right: 0;
    bottom: 0;
    font-size: 12px;
    text-align: center;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.3);
    border-radius: 0px 0px 6px 6px;
    color: #ffffff;
  }

  .productImg-icon {
    position: absolute;
    right: -8px;
    top: -5px;
    font-size: 20px;
    text-align: center;
    color: #7f7f7f;
    background-color: white;
    border-radius: 50px;
  }

  .codeOne {
    display: flex;
    margin-left: 40px;
    align-items: center;
    margin-top: 20px;
  }

  .serveMsg {
    display: flex;
  }

  .shopMsg {
    display: flex;
    padding-top: 10px;
    // margin-left: 20px;
    &__right {
      margin-left: 20px;
      &--wed {
        display: flex;
        align-items: center;
        margin-top: 10px;
        height: 40px;
        &--text {
          margin-top: 10px;
          margin-right: 20px;
        }
      }
    }
  }
}

.goodForm::-webkit-scrollbar {
  display: none;
}

.next {
  width: 1010px;
  position: fixed;
  bottom: 10px;
  padding: 15px 0px;
  display: flex;
  justify-content: center;
  box-shadow: 0 0px 10px 0px #d5d5d5;
  background-color: white;
  margin-left: -14px;
  z-index: 100;
}

.w-e-text-container {
  height: 532px !important; /*!important是重点，因为原div是行内样式设置的高度300px*/
}
</style>
